package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author WeakMoon
 * @date 2024/12/09 16:10:04
 * 转换器工厂，批量制造转换器
 */

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    //重写创建转化器的方法getConverter
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //循环获取枚举的getCode和source进行对比
                for (T enumConstant : targetType.getEnumConstants()) {
                    //若相同返回类型
                    if (enumConstant.getCode() == Integer.parseInt(source)){
                        return enumConstant;
                    }
                }
                //循环后没有则抛出异常
                throw new RuntimeException("非法类型异常");
            }
        };
    }
}
